﻿using System;
using CorruptedSmileStudio.MessageBox;
using Flaschengeist.Entities;
using UnityEngine;

namespace Flaschengeist.Views 
{
	public class SubmitScoreView : BaseView 
	{
		private ScoreItem scoreItem;
		private string playerName = "nickname";
		private int maxPlayerNameLength = 16;
		private int score;
		private Texture2D header;
		private Texture2D background;
		private GUISkin skin;
		
		public void Start()
		{
			skin = (GUISkin)Resources.Load (Settings.GUI_SKIN_LARGE_TEXT);
			header = (Texture2D)Resources.Load("textures/gui_submitHeader");
			background = (Texture2D)Resources.Load("textures/gui_menuBackground");
		}
		
		public void UpdateScore(int score)
		{
			this.score = score;
		}
		
		public void OnGUI()
		{	
			if (IsActive)
			{	
				GUI.skin = skin;	
				GUI.DrawTexture(new Rect(Screen.width/2 - 163, Screen.height/2 - 125, 326, 270),background);
				GUI.DrawTexture(new Rect(Screen.width/2 - 163, Screen.height/2 - 250, 326, 198),header);
						
				GUI.Label(new Rect(Screen.width/2 - Settings.GUI_BUTTON_WIDTH/2, Screen.height/2 - 100 + 60, Settings.GUI_BUTTON_WIDTH, 25), "Score: " +score.ToString());
						
				if(Event.current.Equals(Event.KeyboardEvent ("return")) 
					|| GUI.Button(new Rect(Screen.width/2 - Settings.GUI_BUTTON_WIDTH/2, Screen.height/2 - 100 + 150, Settings.GUI_BUTTON_WIDTH, Settings.GUI_BUTTON_HEIGHT), "submit"))
				{			
					scoreItem = new ScoreItem();					
					scoreItem.PlayerName = playerName;
					scoreItem.Score = score;
					
					if (!string.IsNullOrEmpty(playerName))
					{
						Hide();
						Submit(scoreItem);
					}
					else
					{
						Hide();
						MessageBox.Show(
							(r) => Show(), 
							"The nickname can't be empty!", 
							"Error", 
							MessageBoxButtons.OK, 
							MessageBoxIcon.Error);
					}
				}
				else if (GUI.Button(new Rect(Screen.width/2 - Settings.GUI_BUTTON_WIDTH/2, Screen.height/2 - 100 + 190, Settings.GUI_BUTTON_WIDTH, Settings.GUI_BUTTON_HEIGHT), "cancel"))
				{
					Hide();
					Abort();
				}
				
				GUI.SetNextControlName("playerNameTextField");		
				playerName = GUI.TextField(new Rect(Screen.width/2 - Settings.GUI_BUTTON_WIDTH/2, Screen.height/2 - 100 + 100, 180, 30), playerName, maxPlayerNameLength);
				GUI.FocusControl("playerNameTextField");
			}
		}
				
		public event Action<ScoreItem> Submit;
		public event Action Abort;
	}
}
